package com.atguigu.gulimall.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.authserver.constant.SmsConstant;
import com.atguigu.gulimall.authserver.feign.MemberFeign;
import com.atguigu.gulimall.authserver.util.HttpUtils;
import com.atguigu.gulimall.authserver.vo.HttpResponseVo;
import com.atguigu.gulimall.authserver.vo.MemberEntity;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@Controller
public class OAuthController {
    @Autowired
    private MemberFeign memberFeign;
    @GetMapping("/oauth2.0/weibo/success")
    public String login(@RequestParam String code, HttpSession session) throws Exception {
        String client_id = "1237145979";
        String client_secret = "18852f2b586a8cd66264295d33ef8679";
        String grant_type = "authorization_code";
        String redirect_uri = "http://auth.gulimall.com/oauth2.0/weibo/success";
        Map<String,String> map = new HashMap<>();
        map.put("client_id",client_id);
        map.put("client_secret",client_secret);
        map.put("grant_type",grant_type);
        map.put("redirect_uri",redirect_uri);
        map.put("code",code);

        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(), null, map);

        if(response.getStatusLine().getStatusCode()==200){
            String json = EntityUtils.toString(response.getEntity());
            HttpResponseVo httpResponseVo = JSON.parseObject(json, HttpResponseVo.class);

            R r = memberFeign.login(httpResponseVo);

            if(r.getCode()==0){
                com.atguigu.common.vo.MemberEntity memberEntity = r.getData("data", new TypeReference<com.atguigu.common.vo.MemberEntity>() {});
                session.setAttribute(SmsConstant.SPRING_SESSION_REDIS_KEY,memberEntity);
                return "redirect:http://gulimall.com";
            }else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        }else {
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
